# -*- coding:utf-8 -*-
#测试pr
import pygame
import sys
import random
import time
# 全局定义
rectWidth = 25
cols = 25
rows = 25
rectIndexs = set(range(0,cols*rows))
SCREEN_Width = cols*rectWidth
SCREEN_Height = rows*rectWidth
#判断首次运行标识
initFlag = True
def index2rect(index):
    x = index % cols
    y = (index-x) / cols
    return pygame.Rect(x*rectWidth,y*rectWidth,rectWidth,rectWidth)
def rect2index(rect):
    x = rect.x/rectWidth
    y = rect.y/rectWidth
    return y*cols+x
def index2xy(index):
    x = index % cols
    y = (index-x) / cols
    return (x,y)
def xy2index(x,y):
    return y*cols+x
# 蛇类
# 点以25为单位
class Snake(object):
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self):
        self.dirction = pygame.K_RIGHT
        self.tmpDirction = pygame.K_RIGHT
        self.body = []
        self._isdead = False
        for x in range(5):
            self.addnode()
        
    # 无论何时 都在前端增加蛇块
    def addnode(self):
        if self.tmpDirction != self.dirction:
            self.dirction =self.tmpDirction 
        index = 0
        if self.body:
            index = self.body[0]
        (x,y) = index2xy(index)
        if self.dirction == pygame.K_LEFT:
            x -= 1                
        elif self.dirction == pygame.K_RIGHT:
            x += 1
        elif self.dirction == pygame.K_UP:
            y -= 1
        elif self.dirction == pygame.K_DOWN:
            y += 1
        # 撞墙
        if x<0 or x >= cols or y<0 or y >= rows:
            self._isdead=True
            return
            
        index = xy2index(x,y)
        self.body.insert(0,index)
        if index in rectIndexs:
            rectIndexs.remove(index)
        
    # 删除最后一个块
    def delnode(self):
        index = self.body.pop()
        if index not in rectIndexs:
            rectIndexs.add(index)
        
    # 死亡判断
    def isdead(self):
        if self._isdead:
            return True
        index = self.body[0]
        
        # 撞自己
        if index in self.body[1:]:
            return True
        return False
        
    # 移动！
    def move(self):
        self.addnode()
        self.delnode()
        
    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self,curkey):
        LR = [pygame.K_LEFT,pygame.K_RIGHT]
        UD = [pygame.K_UP,pygame.K_DOWN]
        if curkey in LR+UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            #此处添加tmpDirction过渡用，以防手速过快反向吃自己。举个例子蛇向右移动，快速按下‘上’‘左’，
            #按下‘上’时方向改变但是未移动，再按下‘左’和当前运动方向相反，蛇移动判定吃自己结束游戏。
            self.tmpDirction = curkey
       
       
# 食物类
# 方法： 放置/移除
# 点以25为单位
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-rectWidth,0,rectWidth,rectWidth)
        self.timer = time.clock()
    def remove(self):
        self.rect.x=-rectWidth
    
    def set(self):

        if self.rect.x == -rectWidth or (time.clock() - self.timer >= 5):
            self.timer = time.clock()
            index = random.choice(list(rectIndexs))
            self.rect = index2rect(index)
            
def show_text(screen, pos, text, color, font_bold = False, font_size = 60, font_italic = False):   
    #获取系统字体，并设置文字大小  
    cur_font = pygame.font.SysFont("宋体", font_size)  
    #设置是否加粗属性  
    cur_font.set_bold(font_bold)  
    #设置是否斜体属性  
    cur_font.set_italic(font_italic)  
    #设置文字内容  
    text_fmt = cur_font.render(text, 1, color)  
    #绘制文字  
    screen.blit(text_fmt, pos)

def drawEye(screen,ret):
    position = int(ret.left+ret.width/2) , int(ret.top+ret.height/2)
    pygame.draw.circle(screen, (255,0,0), position, 10, 10)
def main():
    global initFlag
    pygame.init()
    screen_size = (SCREEN_Width,SCREEN_Height)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    scores = 0
    isdead = False
    
    #初始化地图
    for x in range(0,rows):
        for y in range(0,cols):
            rectIndexs.add(xy2index(x,y))
    # 蛇/食物
    snake = Snake()
    food = Food()
    startTime = time.clock()
    baseFps = 10
    fps=baseFps
    nightFlag = False

    while True:
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_SPACE]:
            fps=min(fps+2,30)
        else:
            fps=baseFps
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit(0)
            
            if event.type == pygame.KEYDOWN:
                snake.changedirection(event.key)
                # 死后按space重新
                if event.key == pygame.K_SPACE and isdead:
                    initFlag = False
                    return main()
        isdead = snake.isdead()   
        if nightFlag and not isdead:
            screen.fill((0,0,0))
        else:
            screen.fill((255,255,255))

        if initFlag:
            isdead = True

            show_text(screen,(100,200),'Snake in the Night!',(227,29,18),False,70)
            show_text(screen,(150,260),'press space to start...',(0,0,22),False,30)
        else:
            # 画蛇身 / 每一步+1分
            if not isdead:
                scores+=1
                snake.move()
            if isdead or not nightFlag:
                for tmpIndex in snake.body:
                    rect = index2rect(tmpIndex)
                    pygame.draw.rect(screen,(20,220,39),rect,0)
            
            snakeHead = index2rect(snake.body[0])
            

            # 显示死亡文字
            if isdead:
                show_text(screen,(100,200),'Game over!',(227,29,18),False,100)
                show_text(screen,(150,260),'press space to restart...',(0,0,22),False,30)
                
            # 食物处理 / 吃到+50分
            # 当食物rect与蛇头重合,吃掉 -> Snake增加一个Node
            if food.rect == snakeHead:
                scores+=50
                food.remove()
                snake.addnode()
            if not isdead:
                drawEye(screen,snakeHead)
                # 食物投递
                food.set()
                pygame.draw.rect(screen,(136,0,21),food.rect,0)
                currentTime = int(time.clock()-startTime)
            # 显示分数文字
            show_text(screen,(20,0),'Scores: '+str(scores),(0,162,232),font_size=40)
            show_text(screen,(450,0),'time: '+str(currentTime),(0,162,232),font_size=40)
            if currentTime>=10:
                nightFlag = not nightFlag
                startTime = time.clock()

        pygame.display.update()
        clock.tick(fps)
    
    
if __name__ == '__main__':
    main()